﻿using System;
using FibMatrix.DS;
using UnityEngine;

[FM_Mono.IgnoreGen]
public class PooledAsyncOpCallback:IDisposable
{
    private static ObjectPool2<PooledAsyncOpCallback> _pool = new ObjectPool2<PooledAsyncOpCallback>(-1, ()=>new PooledAsyncOpCallback());
    public PooledAsyncOpCallback()
    {
    }

    private Action<AsyncOperation, object> _asyncCallback;

    private object _context;

    public static PooledAsyncOpCallback Combine(AsyncOperation asyncOperation, Action<AsyncOperation, object> asyncCallback, object context)
    {
        PooledAsyncOpCallback proxy = _pool.Allocate();
        proxy._asyncCallback = asyncCallback;
        proxy._context = context;
        asyncOperation.completed += proxy.OnAsyncOperationComplete;
        return proxy;
    }

    private void OnAsyncOperationComplete(AsyncOperation asyncOp)
    {
        asyncOp.completed -= this.OnAsyncOperationComplete;
        if (this._asyncCallback != null)
        {
            this._asyncCallback(asyncOp, this._context);
        }
        _pool.Recycle(this);
    }

    public void Dispose()
    {
        this._asyncCallback = null;
        this._context = null;
    }
}

